package vip.xiaonuo.listener;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.Reactor;
import reactor.event.Event;
import reactor.function.Consumer;
import vip.xiaonuo.facedoor.modular.device.entity.DeviceCategory;
import vip.xiaonuo.facedoor.modular.memberfeatures.entity.MemberFeatures;
import vip.xiaonuo.facedoor.modular.memberfeatures.param.MemberFeaturesParam;
import vip.xiaonuo.facedoor.modular.memberfeatures.service.MemberFeaturesService;
import vip.xiaonuo.facedoor.modular.memberuser.entity.MemberUser;
import vip.xiaonuo.facedoor.modular.topic.AiBoxEventTopic;
import vip.xiaonuo.megvii.faces.model.FaceDelete;
import vip.xiaonuo.megvii.service.DeviceMegviiFaceService;

import javax.annotation.Resource;

import java.util.List;

import static reactor.event.selector.Selectors.$;

@Service
@Slf4j
public class MemberUserDeleteListener implements Consumer<Event<MemberUser>>, InitializingBean {

    @Autowired
    private Reactor reactor;

    @Resource
    private DeviceMegviiFaceService faceService;

    @Resource
    private MemberFeaturesService featuresService;

    @Override
    public void afterPropertiesSet() throws Exception {
        reactor.on($(AiBoxEventTopic.USER_DELETE), this);
    }

    @Override
    public void accept(Event<MemberUser> event) {
        MemberUser user = event.getData();
        log.info("{}",user);
        this.doUserDelete(user);
    }

    /**
     * 人员删除
     * 1.所有人脸出库处理
     * 本地分组关联的数据会同时删除
     * @param user
     */
    private void doUserDelete(MemberUser user) {
        // 1.先查出当前已有的数据
        MemberFeaturesParam param = new MemberFeaturesParam();
        param.setDwMemberUserId(user.getId());
        param.setPlatform(DeviceCategory.SUB_TYPE_BOX);
        List<MemberFeatures> currentFeatures = featuresService.listByUserId(param);
        for(MemberFeatures feature : currentFeatures){
            if(ObjectUtil.isEmpty( feature.getImageId()) ){// 没有对应的imgid,无法与旷视后台进行交互，该数据直接删除
                featuresService.removeById(feature);
            }else{
                FaceDelete faceDelete = BeanUtil.copyProperties(feature, FaceDelete.class);
                faceDelete.setDeleteMode(1);
                faceService.faceDelete(faceDelete);
            }
        }
    }
}
